import React from 'react';
import {
    Form,
    Input,
    Button,
    Toast
} from 'antd-mobile';
// 引入登录接口
import { loginApi } from '@/api/login';
// 引入dispatch hook 
import { useDispatch } from 'react-redux'
// 引入路由相关的hook
import { useHistory } from 'react-router-dom'

const Myform = () => {
    const dispatch = useDispatch();
    const his = useHistory()
    // 获取form 表单实例
    const [form] = Form.useForm()
    // 表单提交事件
    const onSubmit = () => {
        const values = form.getFieldsValue()
        console.log('values', values);
        loginApi(values).then(res => {
            console.log(res);
            if (res.data.code == 200) {
                // 提示登录成功
                Toast.show({
                    content: '登录成功',
                    afterClose: () => {
                        // afterClose 提示关闭后触发的回调函数 
                        // 跳转首页页面
                        // console.log('after')
                        his.push('/home')
                    },
                })
                // 将用户信息和token 存到本地
                localStorage.setItem('token', res.data.data.token)
                // 将userid 用户信息存到redux中
                dispatch({ type: 'setuser', payload: res.data.data.userid })
            }
        })
    }
    return (
        <>
            <Form
                // 赋值form 表单实例
                form={form}
                layout='horizontal'
                footer={
                    <Button block type='submit' onClick={onSubmit} color='primary' size='large'>
                        登录
                    </Button>
                }
            >
                <Form.Item
                    name='loginname'
                    label='用户名'
                    rules={[{ required: true, message: '用户名不能为空' }]}
                >
                    <Input placeholder='请输入用户名' />
                </Form.Item>
                <Form.Item
                    name='password'
                    label='密码'
                    rules={[{ required: true, message: '密码不能为空' }]}
                >
                    <Input placeholder='请输入密码' />
                </Form.Item>
            </Form>
        </>
    );
}

export default Myform;
